package com.my.socket.aio.v1;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.util.concurrent.Future;

/**
 * User: Alex Zhong
 * Date: 2016/6/17
 */
public class Server {
    private static final Logger LOGGER = LoggerFactory.getLogger(Server.class);

    public static void main(String[] args) throws Exception {
        AsynchronousServerSocketChannel serverSocketChannel = AsynchronousServerSocketChannel.open();
        serverSocketChannel.bind(new InetSocketAddress("127.0.0.1", 9999));

        LOGGER.info("waiting for the client connection at {}", serverSocketChannel.getLocalAddress());
        Future<AsynchronousSocketChannel> future = serverSocketChannel.accept();
        AsynchronousSocketChannel socketChannel = future.get();
        LOGGER.info("handle a connection from the client {}", socketChannel.getRemoteAddress());

        ByteBuffer byteBuffer = ByteBuffer.allocate(15);
        socketChannel.read(byteBuffer).get();
        String message = new String(byteBuffer.array());
        LOGGER.info("receive the message [{}] from the client {}", message, socketChannel.getRemoteAddress());

        message = message.toUpperCase();

        socketChannel.write(ByteBuffer.wrap(message.getBytes())).get();
        LOGGER.info("send the message [{}] to the client {}", message, socketChannel.getRemoteAddress());
    }
}
